import React, { useState, useEffect,useRef } from 'react';
import { Modal, Form, Input, Select, Button, Row, Col, message, DatePicker, notification } from 'antd';
import { querySysmemberList, queryTagList, updateTask,queryCarDetail} from '../service';
import moment from 'moment';

const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };

const UpdateForm = ({ modalVisible, onCancel, data, onConfirm }) => {
  const [driverList, setDriverList] = useState([]);
  const [carList, setCarList] = useState([]);
  const [testerList, setTesterList] = useState([]);
  const [tagList, setTagList] = useState([]);
  const [formRef] = Form.useForm();
  const actionRef = useRef();
  useEffect(() => {
    formRef.setFieldsValue(data);
  }, [data, formRef]);
  useEffect(() => {
    queryCarDetail({limit: 100000, offset: 0}).then((data) => {
      // JSON格式转换
      setCarList(JSON.stringify(data.data) !== '{}'? data.data: []);
    });
    queryTagList({ is_active: 1 })
      .then(({ code, data: reap = [], msg }) => {
        if (code === '200') {
          const tagList = reap ?? [];
          const tagId = tagList.find(({ name }) => data?.taskTagName === name);
          if (tagId) {
            formRef.setFieldsValue({ task_tag_id: tagId.id });
          }
          setTagList(reap ?? []);
        } else {
          setTagList([]);
        }
      })
      .catch(() => {
        setTagList([]);
      });
    querySysmemberList({ type: 1 })
      .then(({ code, data: reap = [], msg }) => {
        if (code === '200') {
          const driverList = reap ?? [];
          const tagId = driverList.find(({ name }) => data?.driverName === name);
          if (tagId) {
            formRef.setFieldsValue({ driver_id: tagId.id });
          }
          setDriverList(driverList);
        } else {
          setDriverList([]);
        }
      })
      .catch(() => {
        setDriverList([]);
      });
    querySysmemberList({ type: 2 })
      .then(({ code, data: reap = [], msg }) => {
        if (code === '200') {
          const testerList = reap ?? [];
          const testerId = testerList.find(({ name }) => data?.testorName === name);
          if (testerId) {
            formRef.setFieldsValue({ tester_id: testerId.id });
          }
          setTesterList(testerList);
        } else {
          setTesterList([]);
        }
      })
      .catch(() => {
        setTesterList([]);
      });
  }, [data?.driverName, data?.taskTagName, data?.testorName, formRef]);
  const onFinish = (values) => {
    const { dateTime, ...formItems } = values;
    updateTask({
      ...formItems,
      start_time: moment(dateTime[0]).format('YYYY-MM-DD HH:mm:ss'),
      end_time: moment(dateTime[1]).format('YYYY-MM-DD HH:mm:ss'),
    })
      .then(({ code, msg }) => {
        if (String(code) === '200') {
          onConfirm();
          message.success('修改成功！');
        } else {
          message.warning(msg || '修改失败！');
        }
      })
      .catch(() => {
        notification.warning({ message: '异常', description: '网络异常！' });
      });
  };
  
  return (
    <Modal
      width={800}
      destroyOnClose
      title="预约更新"
      visible={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <Form form={formRef} {...layout} initialValues={data} onFinish={onFinish} >
        {/* <Row>
          <Col lg={{ span: 8 }} md={{ span: 8 }} sm={{ span: 12 }} align="right">
            <div style={{ margin: '10px 0' }}>车辆：</div>
          </Col>
          <Col lg={{ span: 16 }} md={{ span: 16 }} sm={{ span: 12 }}>
            <div style={{ margin: '10px 0' }}>{data.card}</div>
          </Col>
        </Row> */}
        <Form.Item name="card" label="车辆" rules={[{ required: false }]}>
          <Select>
          {carList.map((item) => (
              <Select.Option value={item.card} key={item.card}>
                {item.card}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="id" label="id" rules={[{ required: true }]} hidden>
          <Input />
        </Form.Item>
        <Form.Item name="status" label="status" rules={[{ required: true }]} hidden>
          <Input />
        </Form.Item>
        <Form.Item name="dateTime" label="预约时间" rules={[{ required: true }]}>
          <DatePicker.RangePicker
            showTime
            secondStep={60}
          minuteStep = {30}
           disabledTime={() => ({ disabledHours: () => [0, 1, 2, 3, 4, 5, 6, 7, 23, 24]})} 
       
          />
        </Form.Item>
        {/* <Row>
          <Col lg={{ span: 8 }} md={{ span: 8 }} sm={{ span: 12 }} align="right">
            <div style={{ margin: ' 0 0 15px 0' }}>预约人：</div>
          </Col>
          <Col lg={{ span: 16 }} md={{ span: 16 }} sm={{ span: 12 }}>
            <div style={{  margin: ' 0 0 15px 0'  }}>{data.creatorName}</div>
          </Col>
        </Row> */}
        <Form.Item name="driver_id" label="司机" rules={[{ required: false }]}>
          <Select>
            {driverList.map(({ name, id }, index) => (
              <Select.Option key={id} value={id}>
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="tester_id" label="测试人员" rules={[{ required: false }]}>
          <Select>
            {testerList.map(({ name, id }, index) => (
              <Select.Option key={id} value={id}>
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="task_tag_id" label="任务标签" rules={[{ required: false }]}>
          <Select>
            {tagList.map(({ name, id }, index) => (
              <Select.Option key={id} value={id}>
                {name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="content" label="任务内容" rules={[{ required: false }]}>
          <Input.TextArea maxLength={256}/>
        </Form.Item>
        <Row>
          <Col lg={{ offset: 6 }} md={{ offset: 8 }} sm={{ offset: 12 }}>
            <Button onClick={() => onCancel()}>取消</Button>
            </Col>
            <Col push={4} lg={{ offset: 6 }} md={{ offset: 8 }} sm={{ offset: 12 }}>
            <Button htmlType="submit">保存</Button>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default UpdateForm;
